﻿using Furion.JsonSerialization;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WxCore.Entity;
using WxCore.Sqlsugar;

namespace WxCore.Service
{
    /// <summary>
    /// 主数据Service基类，提供主数据Entity增删改查的通用方法
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseMainService<TEntity> where TEntity : BaseMainEntity, new()
    {
        /// <summary>
        /// 
        /// </summary>
        public SqlSugarRepository<TEntity> repo { get; set; }

        /// <summary>
        /// 查询单个实体详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<TEntity> SingleAsync(string id)
        {
            var main = await repo.GetSingleAsync(t => t.id == id);

            return main;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<string> InsertAsync(TEntity entity)
        {
            var id = "";
            if (string.IsNullOrEmpty(entity.id))
            {
                id = SnowFlakeSingle.instance.NextId().ToString(); //雪花ID
                entity.id = id; //雪花ID
            }

            entity.crtim = DateTime.Now;
            entity.avtag = true;

            await repo.InsertAsync(entity);

            return id;
        }

        //新增
        public async Task<string> InsertAsyncByPlc(TEntity entity)
        {
            if (string.IsNullOrEmpty(entity.id))
            {
                entity.id = SnowFlakeSingle.instance.NextId().ToString(); //雪花ID
            }

            entity.crtim = DateTime.Now;
            entity.avtag = true;

            await repo.InsertAsync(entity);
            return entity.id;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<string> UpdateAsync(TEntity entity)
        {
            entity.uptim = DateTime.Now;
            await repo.UpdateAsync(entity);
            return entity.id;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task DeleteAsync(string ids)
        {
            var idArr = ids.Split(",");
            await repo.Context.Deleteable<TEntity>().In(idArr).ExecuteCommandAsync();
        }
    }
}
